package com.unlcn.ils.wms.backend.util;

import jodd.util.StringUtil;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

public class SendMail {

    private static Logger logger = LoggerFactory.getLogger(SendMail.class);


    public static void sendMailMess(String hostUrl, String user, String pwd,
                                    String title, String content, String receipts, String ccs) {
        logger.info("OrderManagerController.sendMailMess AddressException", " hostUrl:" + hostUrl + " user:" +
                " pwd" + pwd + " title:" + title + " content:" + content + " receipts:" + receipts + " ccs:" + ccs);

        try {
            // 配置发送邮件的环境属性
            Properties props = new Properties();
            // 开启debug调试
            props.setProperty("mail.debug", "true");
            // 发送服务器需要身份验证
            props.setProperty("mail.smtp.auth", "true");
            // 设置邮件服务器主机名
            props.setProperty("mail.host", "mail.unlcn.com");
            // 发送邮件协议名称
            props.setProperty("mail.user", user);
            // 发送邮件协议名称
            props.setProperty("mail.pwd", pwd);
            // 发送邮件协议名称
            props.setProperty("mail.transport.protocol", "smtp");

            // 构建授权信息，用于进行SMTP进行身份验证
            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    // 用户名、密码
                    String userName = props.getProperty("mail.user");
                    String password = props.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            };

            // 使用环境属性和授权信息，创建邮件会话
            Session mailSession = Session.getInstance(props, authenticator);
            // 创建邮件消息
            MimeMessage message = new MimeMessage(mailSession);

            // 设置发件人
            InternetAddress form = new InternetAddress(props.getProperty("mail.user"));

            message.setFrom(form);
            // 设置收件人
            message.setRecipients(Message.RecipientType.TO, getReceipts(receipts));
            // 设置抄送人
            message.setRecipients(Message.RecipientType.CC, getCC(ccs));
            // 设置邮件标题
            message.setSubject(title);
            // 设置邮件的内容体
            message.setContent(content, "text/html;charset=UTF-8");
            // 发送邮件
            Transport transport = mailSession.getTransport();
            // 连接邮件服务器
            transport.connect(props.getProperty("mail.user"), props.getProperty("mail.pwd"));
            // 发送邮件 。设置收件人
            transport.sendMessage(message, getReceipts(receipts));
            // 关闭连接
            transport.close();
        } catch (Exception e) {
            logger.error("OrderManagerController.sendMailMess AddressException", e);
        }
    }

    public static void main(String[] args) {
        sendMailHaveFile("", "", "", "", "", "1185665364@qq.com", "1185665364@qq.com", "D:\\project\\company_project\\ils-wms-extra\\ils-wms-extra-api\\src\\main\\resources\\inboundxls/test.js");
        System.out.println("success");
    }

    public static void sendMailHaveFile(String hostUrl, String user, String pwd,
                                        String title, String content, String receipts, String ccs,
                                        String... files) {
        logger.error("SendMail.sendMailHaveFile params {}" + "hostUrl:" + hostUrl + " user:" + user + " pwd:" + pwd
                + " title:" + title + " content:" + content + " receipts:" + receipts + " ccs:" + ccs + " files:" + files);
        try {
            // 配置发送邮件的环境属性
            Properties props = new Properties();
            // 开启debug调试
            props.setProperty("mail.debug", "true");
            // 发送服务器需要身份验证
            props.setProperty("mail.smtp.auth", "true");
            // 设置邮件服务器主机名
            props.setProperty("mail.host", "mail.unlcn.com");
            // 发送邮件协议名称
            props.setProperty("mail.user", "ils@unlcn.com");
            // 发送邮件协议名称
            props.setProperty("mail.pwd", "Unlcn@2016");
            // 发送邮件协议名称
            props.setProperty("mail.transport.protocol", "smtp");

            // 构建授权信息，用于进行SMTP进行身份验证
            Authenticator authenticator = new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    // 用户名、密码
                    String userName = props.getProperty("mail.user");
                    String password = props.getProperty("mail.password");
                    return new PasswordAuthentication(userName, password);
                }
            };

            // 使用环境属性和授权信息，创建邮件会话
            Session mailSession = Session.getInstance(props, authenticator);
            // 创建邮件消息
            MimeMessage message = new MimeMessage(mailSession);

            // 设置发件人
            InternetAddress form = new InternetAddress(props.getProperty("mail.user"));
            message.setFrom(form);
            // 设置收件人
            message.setRecipients(Message.RecipientType.TO, getReceipts(receipts));
            // 设置抄送人
            if (!StringUtil.isEmpty(ccs)) {
                message.setRecipients(Message.RecipientType.CC, getCC(ccs));
            }
            // 设置邮件标题
            message.setSubject(title);
            message.addHeader("charset", "UTF-8");
            // 添加正文内容*/
            Multipart multipart = new MimeMultipart();
            BodyPart contentPart = new MimeBodyPart();
            contentPart.setText(content);
            contentPart.setHeader("charset", "UTF-8");
            multipart.addBodyPart(contentPart);
            // 添加附件
            for (String file : files) {
                File usFile = new File(file);
                MimeBodyPart fileBody = new MimeBodyPart();
                DataSource source = new FileDataSource(file);
                fileBody.setDataHandler(new DataHandler(source));
                Base64 base64 = new Base64();
                //sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
                fileBody.setFileName("=?UTF-8?B?" + base64.encodeToString(usFile.getName().getBytes()) + "?=");
                multipart.addBodyPart(fileBody);
            }

            message.setContent(multipart);
            message.setSentDate(new Date());
            message.saveChanges();
            Transport transport = mailSession.getTransport("smtp");

            // 连接邮件服务器
            transport.connect(props.getProperty("mail.user"), props.getProperty("mail.pwd"));
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            logger.error("SendMail.sendMailHaveFile end===============");
        } catch (Exception e) {
            logger.error("SendMail.sendMailHaveFile Exception", e);
        }
    }

    /**
     * 获取收货人
     */
    private static InternetAddress[] getReceipts(String receipts) {
        // 多个接收账号
        InternetAddress[] address = null;
        try {
            List<InternetAddress> list = new ArrayList<>();
            String[] median = receipts.split(";");
            for (int i = 0; i < median.length; i++) {
                list.add(new InternetAddress(median[i]));
            }
            address = (InternetAddress[]) list.toArray();
        } catch (AddressException e) {
            logger.error("OrderManagerController.getReceipts AddressException", e);
        }
        return address;
    }

    /**
     * 获取抄送人
     */
    private static InternetAddress[] getCC(String ccs) {
        // 多个接收账号
        InternetAddress[] address = null;
        try {
            List<InternetAddress> list = new ArrayList<>();
            String[] median = ccs.split(";");
            for (int i = 0; i < median.length; i++) {
                list.add(new InternetAddress(median[i]));
            }
            address = (InternetAddress[]) list.toArray();
        } catch (AddressException e) {
            logger.error("OrderManagerController.getCC AddressException", e);
        }
        return address;
    }
}
